<template>
    <div>
        <!--<a-button class="editable-add-btn" @click="handleAdd" style="margin-bottom: 8px" type="primary">新增</a-button>-->
        <a-button type="primary" @click="openNewStudent" style="margin-top:15px">新增</a-button>
        <a-modal
                title="新增学生表信息"
                okText='新增'
                cancel-text="取消"
                v-model:visible="visible"
                :confirm-loading="confirmLoading"
                @ok="handleAdd"
        >
            <a-form  :label-col="labelCol"  :rules="rulesRef" ref="formRef" :model="student">
                <a-row >
                            
                <a-form-item label="姓名" name="name"  >
                    <a-input v-model:value="student.name"/>
                </a-form-item>
                <a-form-item label="学号" name="studentID">
                    <a-input v-model:value="student.studentID"/>
                </a-form-item>
                          
                </a-row >

      
                <a-form-item  style="float:left" label="班级" name="classID">
                    <a-input v-model:value="student.classID"/>
                </a-form-item>


                <a-form-item label="性别" name="sex">
                    <a-select  placeholder="性别" v-model:value="student.sex">
                        <a-select-option value="男">男</a-select-option>
                        <a-select-option value="女">女</a-select-option>
                    </a-select>
                      
                    
                </a-form-item>
       

            </a-form>
        </a-modal>
        <a-modal
                title="编辑学生表信息"
                okText='保存'
                cancel-text="取消"
                v-model:visible="visibleOfChangeView"
                :confirm-loading="confirmLoading"
                @ok="handleChange"
        >
            <a-form :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rulesRef" ref="formRef" :model="student">
                <a-row >
                <a-form-item label="姓名" name="name">
                    <a-input v-model:value="student.name"/>
                </a-form-item>
                <a-form-item label="学号" name="studentID">
                    <a-input v-model:value="student.studentID"/>
                </a-form-item>
                </a-row >
                
                <a-form-item  style="float:left" label="班级" name="classID">
                    <a-input v-model:value="student.classID"/>
                </a-form-item>

                <a-form-item label="性别" name="sex">
                    <a-select  placeholder="性别" v-model:value="student.sex">
                        <a-select-option value="男">男</a-select-option>
                        <a-select-option value="女">女</a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
        </a-modal>



        <a-table bordered 
        :data-source="dataSource"
        :columns="columns" 
        :pagination="pagination"
        style="margin-top:15px"
        
         >
            <template #filterDropdown="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }">
                <div style="padding: 8px" v-if="column.title !== '操作'">
                    <a-input
                            ref="searchInput"
                            :placeholder="`Search ${column.dataIndex}`"
                            :value="selectedKeys[0]"
                            style="width: 188px; margin-bottom: 8px; display: block"
                            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                            @pressEnter="handleSearch(selectedKeys, confirm, column.dataIndex)"
                    />
                    <a-button
                            type="primary"
                            size="small"
                            style="width: 90px; margin-right: 8px"
                            @click="handleSearch(selectedKeys, confirm, column.dataIndex)"
                    >
                        <template #icon><SearchOutlined /></template>
                        Search
                    </a-button>
                    <a-button size="small" style="width: 90px" @click="handleReset(clearFilters)">
                        Reset
                    </a-button>
                </div>
            </template>
            <template #filterIcon="filtered">
                <search-outlined :style="{ color: filtered ? '#108ee9' : undefined }"  />
            </template>


            <template #operation="{ record }">
                <a @click="openChangeStudent(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm
                        v-if="dataSource.length"
                        title="是否确定删除？"
                        @confirm="onDelete(record.key)"
                >
                    <a>删除</a>
                </a-popconfirm>

                <a-divider type="vertical" />
                <a @click="MoreAction">更多操作</a>
            </template>


        </a-table>
    </div>

</template>
<script>
    import { computed, defineComponent, reactive, ref } from 'vue';
    import { CheckOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons-vue';
    import { cloneDeep } from 'lodash-es';
    import { useForm } from '@ant-design-vue/use';
    import axios from "axios";
    import router from "../../router";
    import {useStore} from "vuex";
    export default defineComponent({
        name: "StudentForm",
        components: {
            CheckOutlined,
            EditOutlined,
            SearchOutlined,
        },

       

        setup() {
            

            /**
             * 查询功能
             * 可模糊查询与多属性联合模糊查询
             * 参考ant design vue的自定义筛选菜单表格
             * */
            const state = reactive({
                searchText: '',
                searchedColumn: '',
            });
            const searchInput = ref();

            const handleSearch = (selectedKeys, confirm, dataIndex) => {
                confirm();
                state.searchText = selectedKeys[0];
                state.searchedColumn = dataIndex;
            };

            const handleReset = clearFilters => {
                clearFilters();
                state.searchText = '';
            };

            /**
             * 与表单输入框绑定的输入数据
             * 新增
             * 编辑
             * */
            const student = reactive({
                key: '',
                name: '',
                studentID: '',
                classID: '',
                sex: '',
            });

            /**
             * 数据类型
             * */
            const columns = [
                {
                    title: '姓名',
                    dataIndex: 'name',
                    key: 'name',
                    width: '20%',
                    slots: {
                        customRender: 'name',
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                    },
                    onFilter: (value, record) =>
                        record.name.toString().toLowerCase().includes(value.toLowerCase()),
                    onFilterDropdownVisibleChange: visible => {
                        if (visible) {
                            setTimeout(() => {
                                console.log(searchInput.value);
                                searchInput.value.focus();
                            }, 0);
                        }
                    },
                },
                {
                    title: '学号',
                    dataIndex: 'studentID',
                    key: 'studentID',
                    width: '20%',
                    slots: {
                        customRender: 'studentID',
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                    },
                    onFilter: (value, record) =>
                        record.studentID.toString().toLowerCase().includes(value.toLowerCase()),
                    onFilterDropdownVisibleChange: visible => {
                        if (visible) {
                            setTimeout(() => {
                                console.log(searchInput.value);
                                searchInput.value.focus();
                            }, 0);
                        }
                    },

                },
                {
                    title: '班级',
                    dataIndex: 'classID',
                    key: 'classID',
                    width: '20%',
                    slots: {
                        customRender: 'classID',
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                    },
                    onFilter: (value, record) =>
                        record.classID.toString().toLowerCase().includes(value.toLowerCase()),
                    onFilterDropdownVisibleChange: visible => {
                        if (visible) {
                            setTimeout(() => {
                                console.log(searchInput.value);
                                searchInput.value.focus();
                            }, 0);
                        }
                    },
                },
                {
                    title: '性别',
                    dataIndex: 'sex',
                    key: 'sex',
                    width: '20%',
                    slots: {
                        customRender: 'sex',
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                    },
                    onFilter: (value, record) =>
                        record.sex.toString().toLowerCase().includes(value.toLowerCase()),
                    onFilterDropdownVisibleChange: visible => {
                        if (visible) {
                            setTimeout(() => {
                                console.log(searchInput.value);
                                searchInput.value.focus();
                            }, 0);
                        }
                    },
                },
                {
                    title: '操作',
                    key: 'action',
                    dataIndex: 'operation',
                    slots: {
                        customRender: 'operation',
                    }
                },
            ];

            /**
             * 数据源
             * */
            const dataSource = ref();

            /**
             * 新增数据表单中使用的计算属性
             * */
            const count = computed(() => dataSource.value.length + 1);
            const editableData = reactive({});


            /**
             * 删除功能
             * */
            const onDelete = key => {
                dataSource.value = dataSource.value.filter(item => item.key !== key);
            };

            /**
             * 新增功能
             * */
            const visible = ref(false);
            const openNewStudent = () => {

                visible.value = true;
            };
            const handleAdd = () => {
                formRef.value
                    .validate()
                    .then(() => {
                        const newData = {
                            key: `${count.value}`,
                            name: `${student.name}`,
                            studentID: `${student.studentID}`,
                            classID: `${student.classID}`,
                            sex: `${student.sex}`,
                        };
                        visible.value = false;
                        dataSource.value.push(newData);
                    })
                    .catch(error => {
                        console.log('error', error);
                    });
            };

            /**
             * 编辑功能
             * */
            const visibleOfChangeView = ref(false);
            const openChangeStudent = record => {
                student.key = record.key;
                student.name = record.name;
                student.studentID = record.studentID;
                student.classID = record.classID;
                student.sex = record.sex;
                visibleOfChangeView.value = true;
            };
            const handleChange = () => {
                formRef.value
                    .validate()
                    .then(() => {
                        const newData = {
                            key: `${student.key}`,
                            name: `${student.name}`,
                            studentID: `${student.studentID}`,
                            classID: `${student.classID}`,
                            sex: `${student.sex}`,
                        };
                        student.key = '';
                        student.name = '';
                        student.studentID = '';
                        student.classID = '';
                        student.sex = '';
                        visibleOfChangeView.value = false;
                        Object.assign(dataSource.value.filter(item => newData.key === item.key)[0], newData);
                        /*dataSource.value.push(newData);*/
                    })
                    .catch(error => {
                        console.log('error', error);
                    });
            };

            /**
             * 表单验证功能
             * */
            const formRef = ref();
            const rulesRef = reactive({
                name: [
                    {
                        required: true,
                        message: 'Please input name',
                        trigger: 'blur',
                    },
                ],
                studentID: [
                    {
                        required: true,
                        message: 'Please input studentID',
                        trigger: 'blur',
                    },
                ],
                classID: [
                    {
                        required: true,
                        message: 'Please input classID',
                        trigger: 'blur',
                    },
                ],
                sex: [
                    {
                        required: true,
                        message: 'Please select sex',
                        trigger: 'change',
                    },
                ],
            });

            /*const modalText = ref('Content of the modal');*/
            const confirmLoading = ref(false);
            
            const pagination={
        defaultPageSize: 8,
        showTotal: (total) => `共 ${total} 条数据`,
        // showSizeChanger: true, //是否可以改变 pageSize
        // pageSizeOptions: ["5", "10", "15", "20"],
        // onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize),
      };

      const MoreAction = () => {
          alert("待开发")
      };

            return {
                pagination,
                state,
                handleSearch,
                handleReset,
                searchInput,
                formRef,
                student,
                visible,
                visibleOfChangeView,
                rulesRef,
                confirmLoading,
                openNewStudent,
                openChangeStudent,
                handleChange,
                columns,
                onDelete,
                handleAdd,
                dataSource,
                editableData,
                count,
                labelCol: {
                    span: 4,
                },
                wrapperCol: {
                    span: 14,
                },
                MoreAction,
                
            };
        },
        /**
         * mock模拟数据接口给dataSource赋值
         * */
        async beforeMount() {
            const students = await axios.get('/api/students');
            this.dataSource = students.data;
            console.log(students.data);
        }
    });
</script>
<style lang="less">
    .editable-cell {
        position: relative;
        .editable-cell-input-wrapper,
        .editable-cell-text-wrapper {
            padding-right: 24px;
        }

        .editable-cell-text-wrapper {
            padding: 5px 24px 5px 5px;
        }

        .editable-cell-icon,
        .editable-cell-icon-check {
            position: absolute;
            right: 0;
            width: 20px;
            cursor: pointer;
        }

        .editable-cell-icon {
            margin-top: 4px;
            display: none;
        }

        .editable-cell-icon-check {
            line-height: 28px;
        }

        .editable-cell-icon:hover,
        .editable-cell-icon-check:hover {
            color: #108ee9;
        }

        .editable-add-btn {
            margin-bottom: 8px;
        }
    }
    .editable-cell:hover .editable-cell-icon {
        display: inline-block;
    }
</style>